<?php

namespace frontend\modules\business\controllers;


use common\models\business\BusinessAdress;
use common\models\business\BusinessFarmers;
use common\models\business\BusinessPig;
use common\models\business\NewBusinessInspection;
use common\models\business\NewBusinessInspectionData;
use common\models\shop\ShopHouseOrder;
use common\models\shop\ShopOrder;
use common\models\shop\ShopRaisingOrder;
use common\models\sys\SysSetting;
use frontend\controllers\BaseMobileController;
use yii\db\Query;
use yii\helpers\ArrayHelper;


/*
 * 领导手机查阅统计
 */
class LeaderController extends BaseMobileController
{


    public static $menus = [];



    public function beforeAction($action)
    {

        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }


    public function init()
    {
        self::$menus = [
            ['name' => '农户统计','icon'=>"xiaoxi",'color'=>"mx_green",'link' => 'farmer'],
            ['name' => '仔猪统计','icon'=>"pencil",'color'=>"danger",'link' => 'pig'],
            ['name' => '巡检统计','icon'=>"menu",'color'=>"info",'link' => 'inspection'],
            ['name' => '订单统计','icon'=>"user",'color'=>"mx_green",'link' => 'order'],
            ['name' => '仔猪重分布','icon'=>"telephone",'color'=>"danger",'link' => 'weight'],
        ];
        parent::init(); // TODO: Change the autogenerated stub
    }




    /**
     * @return string
     * 个人中心
     */
    public function actionIndex()
    {
        return $this->render('@template/mobile/leader/leader_index.html',[
            'menus' => \GuzzleHttp\json_encode(self::$menus),
            'user' => $this->user
        ]);

    }


    /**
     * @return string
     * 农户统计
     */
    public function actionFarmer()
    {
        $farmer = (new Query())->select('count(*) as num,villageid,a.name')
            ->from(BusinessFarmers::tableName().' as f')
            ->leftJoin(BusinessAdress::tableName().' as a','f.villageid=a.id')
            ->where('a.status=:status and a.type=:type and f.status=:fstatus and f.ispoor=:poor',[
                ':status'=>BusinessAdress::STATUS_ACTIVE,
                ':type'=>BusinessAdress::TYPE_CUN,
                ':fstatus' => BusinessFarmers::STATUS_AGREE,
                ':poor' => BusinessFarmers::IS_POOR,
            ])
            ->groupBy('villageid')
            ->indexBy('villageid')
            ->all();

        $poordata = [];
        $poorname = [];
        $poor = [];
        foreach ($farmer as $key => $row){
            $poordata[] = [
                'value' => intval($row['num']),
                'name' => $row['name'],
            ];
            $poor[$row['name']] = $row['num'];
            $poorname[] = $row['name'];
        }


        $query = (new Query())->select('count(f.id) as num,a.lat,a.lng,a.name,a.id as addressid')->from(BusinessAdress::tableName().' as a')
            ->leftJoin(BusinessFarmers::tableName().' as f','f.villageid=a.id')
            ->where('a.status=:status and a.type=:type and f.status=:fstatus',[
                ':status'=>BusinessAdress::STATUS_ACTIVE,
                ':type'=>BusinessAdress::TYPE_CUN,
                ':fstatus' => BusinessFarmers::STATUS_AGREE,
            ])
            ->groupBy('a.id');


        //农户柱形图
        $fdata = [];
        $total = [];
        foreach ($query->each() as $key => $row){
            $fdata[] = [
                'value' => intval($row['num']),
                'name' => $row['name'],
            ];
            $total[$row['name']] = $row['num'];
            $name[] = $row['name'];
        }

        return $this->render('@template/mobile/leader/leader_farmer.php',[
            'farmer' => $farmer,
            'fdata' => $fdata,
            'name' => $name,
            'poorname' => $poorname,
            'poor' => $poor,
            'poordata' => $poordata
        ]);
    }


    /**
     * @return string
     * 仔猪统计
     */
    public function actionPig()
    {

        //仔猪状态总体统计图
        $list = (new Query())->select(['status','count(id) as num'])->from(BusinessPig::tableName())->groupBy('status')->indexBy('status')->all();
        foreach ($list as $key => $row){
            $row['status'] = BusinessPig::$statues[$row['status']];
            $statusdata['type'][] = $row['status'];
            $statusdata['num'][] = $row['num'];
        }


        $query = (new Query())->select('status,batch')->from(BusinessPig::tableName());

        //取出每个批次的总数
        $total = (new Query())->select('count(*) as total,batch')->from(BusinessPig::tableName())->groupBy('batch')->indexBy('batch')->all();



        //每个批次每种状态分别存放
        foreach ($query->each() as $key => $row) {
            $all[$row['batch']][$row['status']][] = $row;
        }

        $reslut = [];
        foreach ($all as $key => $row){
            foreach (BusinessPig::$statues as $k => $v){        //查看没种状态的数目
                if(array_key_exists($k,$row)){
                    $reslut[$key][$k]['num'] = count($row[$k]);
                }else{
                    $reslut[$key][$k]['num'] = 0;
                }
                $reslut[$key]['total'] = $total[$key]['total'];
                $reslut[$key][$k]['name'] = $v;

            }
        }
        unset($all,$list);


        return $this->render('@template/mobile/leader/leader_pig.php',[
            'statusdata' => $statusdata,
            'result' => $reslut,
        ]);

    }


    /**
     * @return string
     * 巡检统计
     */
    public function actionInspection()
    {

        //先取出两次巡检差距大于规定值的
        $gday = SysSetting::getValue('inspection_cycle');
        $gtime = $gday*3600*24;
        $now = time();
        $difftime = $now-$gtime;

        //取出已经巡检过的仔猪
        $sql = 'SELECT
                    (select count(*) from business_pig where headpersonid=business_personid and status=:status) as total,
                    count(*) as num,
                    business_personid,
                    business_person,
                    FROM_UNIXTIME(createtime,"%Y-%m-%d") as createtime
              FROM business_pig as pig left join
                    (
                        SELECT
                            pigid,max(createtime) as createtime,business_personid,business_person
                        FROM
                            new_business_inspection
                        GROUP BY 
                          pigid
                        ORDER BY
                            max(createtime) DESC
                    ) AS instmp on instmp.pigid=pig.id
                WHERE
                    createtime < :endtime
                AND (pig.status=:status)
                GROUP BY
                    pig.headpersonid
                ORDER BY
                    createtime DESC';

        $list = \Yii::$app->db->createCommand($sql)->bindValues([':status'=>BusinessPig::STATUS_AFTERIN,':endtime'=>$difftime])->queryAll();

//        var_dump($list);exit;
        $sql = 'select count(*) as num,headpersonid as business_personid,headperson as business_person from '.BusinessPig::tableName().' as pig where pig.status=:status and !exists(select id from '.NewBusinessInspection::tableName().' as ins where ins.pigid=pig.id) group by headpersonid';

        $list2 = \Yii::$app->db->createCommand($sql)->bindValues([':status'=>BusinessPig::STATUS_AFTERIN])->queryAll();

        $hasins = ArrayHelper::index($list, 'business_personid');
        $noins = ArrayHelper::index($list2, 'business_personid');



        //取出每个人管理的仔猪总数(是以入栏的)
        $total = (new  Query())->select('count(*) as total,headpersonid')
            ->from(BusinessPig::tableName())
            ->where('status=:status',[':status'=>BusinessPig::STATUS_AFTERIN])
            ->groupBy('headpersonid')
            ->indexBy('headpersonid')
            ->all();

        $recycle_day = SysSetting::getValue('inspection_cycle');

        return $this->render('@template/mobile/leader/leader_inspection.php',[
            'list' => $hasins,
            'list2' => $noins,
            'total' => $total,
            'recycle_day' =>$recycle_day
        ]);

    }


    /**
     * @return string
     * 订单统计
     */
    public function actionOrder()
    {

        $starttime = '2017-05-01';



        //猪肉订单
        $orders = [];
        $query = (new Query())->select(['count(id) as num','FROM_UNIXTIME(createtime,\'%Y-%m-%d\') as time'])
            ->from(ShopOrder::tableName())
            ->where('createtime>=:start and createtime<=:now',[':start'=>strtotime($starttime),':now'=>time()])
            ->groupBy(['FROM_UNIXTIME(createtime,\'%Y-%m-%d\')'])
            ->indexBy('time');

        foreach ($query->batch() as $order) {
            $tmporders = ArrayHelper::getColumn($order,'time');
            $dissdays = \common\components\Helper::dateDifference($starttime,date('Y-m-d'));
            for ($i=0; $i<=$dissdays; $i++){
                $benddata = date('Y-m-d',strtotime($starttime.' +'.$i.' day'));
                if(in_array($benddata,$tmporders)){
                    $orders[] = intval($order[$benddata]['num']);
                }else{
                    $orders[] = 0;
                }
            }
        }
        unset($query);



        //认养订单
        $rasing = [];
        $query = (new Query())->select(['count(id) as num','FROM_UNIXTIME(createtime,\'%Y-%m-%d\') as time'])
            ->from(ShopRaisingOrder::tableName())
            ->where('createtime>=:start and createtime<=:now',[':start'=>strtotime($starttime),':now'=>time()])
            ->groupBy(['FROM_UNIXTIME(createtime,\'%Y-%m-%d\')'])
            ->indexBy('time');

        foreach ($query->batch() as $order) {
            $tmporders = ArrayHelper::getColumn($order,'time');
            $dissdays = \common\components\Helper::dateDifference($starttime,date('Y-m-d'));
            for ($i=0; $i<=$dissdays; $i++){
                $benddata = date('Y-m-d',strtotime($starttime.' +'.$i.' day'));
                if(in_array($benddata,$tmporders)){
                    $rasing[] = intval($order[$benddata]['num']);
                }else{
                    $rasing[] = 0;
                }
            }
        }
        unset($query);


        //农家乐订单
        $house = [];
        $query = (new Query())->select(['count(id) as num','FROM_UNIXTIME(createtime,\'%Y-%m-%d\') as time'])
            ->from(ShopHouseOrder::tableName())
            ->where('createtime>=:start and createtime<=:now',[':start'=>strtotime($starttime),':now'=>time()])
            ->groupBy(['FROM_UNIXTIME(createtime,\'%Y-%m-%d\')'])
            ->indexBy('time');
        foreach ($query->batch() as $order) {
            $tmporders = ArrayHelper::getColumn($order,'time');
            $dissdays = \common\components\Helper::dateDifference($starttime,date('Y-m-d'));
            for ($i=0; $i<=$dissdays; $i++){
                $benddata = date('Y-m-d',strtotime($starttime.' +'.$i.' day'));
                if(in_array($benddata,$tmporders)){
                    $house[] = intval($order[$benddata]['num']);
                }else{
                    $house[] = 0;
                }
            }
        }


        return $this->render('@template/mobile/leader/leader_order.php',[
            'orders' => \GuzzleHttp\json_encode($orders),
            'rasing' => \GuzzleHttp\json_encode($rasing),
            'house' => \GuzzleHttp\json_encode($house)
        ]);

    }


    /**
     * @return string
     * 重量分布
     */
    public function actionWeight()
    {
        //取出最后一次巡检的记录
        $pigs = (new Query())->select('pigid,i.id,val,batch')
            ->from(NewBusinessInspection::tableName().' as i')
            ->leftJoin(NewBusinessInspectionData::tableName().' as idat','i.id=idat.inspectionid')
            ->leftJoin(BusinessPig::tableName().' as pig','i.pigid=pig.id')
            ->where('idat.fieldname=\'体重\'')
            ->orderBy('i.id desc')
            ->groupBy('pigid')
            ->all();


        //取出体重分布数字

        $getweight = \Yii::$app->request->get('weight');
        if(empty($getweight)){
            $weight = [30,60,150];
        }else{
            $weighttmp = explode(',',$getweight);
            foreach ($weighttmp as $k => $value){
                $weight[] = $value;
            }
        }
        $length = count($weight);


        for ($i=0;$i<$length;$i++){
            if($i == 0){       //第一个
                $tabname[] = '<'.$weight[0].'kg';
                $tab[] = $weight[0];
            }else if($i != ($length-1) && $i != 0) {     //在范围内
                $tabname[] = $weight[$i].'kg-'.$weight[$i+1].'kg';
                $tab[] = $weight[$i].'-'.$weight[$i+1];
            }else if($i == ($length-1)){
                $tabname[] = '>'.$weight[$length-1].'kg';
                $tab[] = $weight[$length-1];
            }
        }


        //按批次取出总数
        $total = (new  Query())->select('count(*) as total,batch')->from(BusinessPig::tableName())->groupBy('batch')->indexBy('batch')->all();


//        var_dump($total);exit;
        //按批数将仔猪分开
        $wiarr = [];
        foreach ($pigs as $k => $v){
            $v['val'] = floatval($v['val']);
            for ($i=0;$i<$length;$i++){
                if($v['val'] <= $weight[0]){
                    $wiarr[$v['batch']][$weight[0]][] = $v;
                    break;
                }else if(($i != 0) && ($i != ($length-1)) && ($v['val'] > $weight[$i]) && ($v['val'] <= $weight[$i+1])) {     //在范围内
                    $wiarr[$v['batch']][$weight[$i].'-'.$weight[$i+1]][] = $v;
                    break;
                }else if(($v['val'] >= $weight[$length-1])){
                    $wiarr[$v['batch']][$length-1][] = $v;
                    break;
                }
            }
        }
        return $this->render('@template/mobile/leader/leader_weight',[
            'wiarr' => $wiarr,
            'tabname' => $tabname,
            'tab' => $tab,
            'total' => $total
        ]);

    }








}


?>